<?php
/**
 * Yotaku Shop - yshop
 * @author Creatint<creatint@163.com>
 * @copyright www.yotaku.cn 2016
 */
namespace Home\Model;
use Think\Model;
use Think\Upload;
class OrderModel extends Model{
    public $error   =   '';
    //自动完成
    protected $_auto = array(
        array('number','getNum',1,'callback'),
//        array('status', 0, self::MODEL_INSERT),
        array('pay_status', 0, self::MODEL_INSERT),
        array('deliver_status', 0, self::MODEL_INSERT),
        array('created_at', NOW_TIME, self::MODEL_INSERT),
        array('update_at', NOW_TIME, self::MODEL_BOTH),
    );
    public function getOrder($user_id,$map = array()){
        if(!$user_id){
            $this->error = '无UID';
            return false;
        }
        $map['user_id'] = $user_id;
        $map['status']  = $map['status']?$map['status']:array('gt',0);
        if($res = $this->where($map)->order("status asc")->select()){
           return $res;
        }else{
            $this->error = '获取数据失败';
            return false;
        }

    }

    public function update($data){

        if($data['id']){
            if($data = $this->create($data) && $this->where("id={$data['id']}")->save()){
                return $data;
            }
            $this->error = '更新失败';
        }else{
            if(($data=$this->create($data)) && ($data['id']=$this->add($data))){
                return $data;
            }
            $this->error = '新增失败';
        }
    }

    public function getDetail($id){
        $map = array();
        if(!$id){
            $this->error = 'ID为空';
            return false;
        }
        $map['id'] = $id;
        $res = $this->where($map)->find();
        if($res){
            return $res;
        }else{
            $this->error = '获取订单详情失败';
            return false;
        }
    }

    public function del($id){
        if(empty($id)){
            $this->error = '请选择要删除的订单';
        }
        if(is_numeric($id)){
            $map['id']=$id;
        }elseif(is_string($id)){
            $map = array('id'=>array('IN',trim(implode(',',$id),',')));
        }
        //$res = $this->where($map)->delete();
        if($this->where($map)->delete()){
            return true;
        }else{
            $this->error = '无此条数据';
            return false;
        }
    }
    public function getNum(){
        //TODO::订单号生成
        $number = time() . substr((1000 + session("member.id")),-4);
        return $number;
    }
    public function getError(){
        return $this->error;
    }
}